var Build    = require('../../models/build.js');
var BuildProxy    = require('../../proxy/build.js');
var logger              = require('log4js').getLogger();
var url = require('url');
var config = require('../../config.json');
var nomralController = require('../../util/normalController.js');
var mk_builder_url = url.format(config.mk.builder);
var app_builder_url = url.format(config.app.builder);
var request = require('request');


var uniqueKey = "_id";
var queryKey = [];
var ctrl = nomralController.api(Build, uniqueKey,queryKey);

ctrl.cancelBuilding = function(req,res,next){
    var build_id =  req.params.build_id;
    var build = req.body.data;
    var type = build.type;
    var state = build.state;
    var token = build.token;
    var url = null;
    if(state === 'building'){
        setBuildState(build,'canceling',function(err, data){
            switch (type){
                case 'mk_back':
                    url = mk_builder_url + '/build/progress?progressId=' + token;
                    break;
                case 'app_ios':
                    url = app_builder_url + 'execute?task=buildhot&space='+ token +'&action=cancel';
                    break;
                case 'app_android':
                    url = app_builder_url + 'execute?task=buildhot&space='+ token +'&action=cancel';
                    break;
            }
            request(url, function (error, response, body){
                if(error){
                    return res.format_json(null,500,err);
                }
                setBuildState(build,'canceled',function(err,data){
                    res.format_json(data,200);
                });
            });
        });

    }else{
        res.format_json(null,500,{error:"只有构建中的任务可以被取消！"});
    }


};
function setBuildState(build, state, callback) {
    logger.info('change state of ' + build._id + ' to ' + state);
    build.state = state;
    build.save(callback);
}

module.exports = ctrl;
